import { loginLeave, departmentTree, ajaxGetDictItems, employeeAll } from '@/api/leave'
import { RoleNames } from '@/api/common'
// 循环
export const arrGet = function (arr) {
  return new Promise((resolve) => {
    let aim = []
    function next(arr) {
      arr.map((res) => {
        const {id, name} = res
        aim.push({id, name})
        if (res.children instanceof Array) {
          return next(res.children)
        }
      })
      resolve(aim)
    }
    next(arr)
  })
}

const leave = {
  state: {
    departmentTree: null,
    leaveTypeAll: null,
    roleNameAll: null,
    employeeAll: null
  },
  mutations: {
    SET_DEPARTMENT (state, departments) {
      state.departmentTree = departments
    },
    SET_LEAVE_TYPES (state, leaveTypes) {
      state.leaveTypeAll = leaveTypes
    },
    SET_ROLE_NAMES (state, roleNames) {
      state.roleNameAll = roleNames
    },
    SET_EMPLOYEES (state, employees) {
      state.employeeAll = employees
    }
  },
  getters: {
    departments (state) {
      return state.departmentTree
    },
    employees (state) {
      return state.employeeAll
    },
    leaveTypes (state) {
      return state.leaveTypeAll
    },
    roleNames (state) {
      return state.roleNameAll
    },
  },
  actions: {
    /* 所有部门 */
    setDepartments ({ commit }) {
      departmentTree().then(data => {
        if (data['success']) {
          arrGet(data.data).then((list) => {
            commit('SET_DEPARTMENT', list)
          }, () => {})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    setLeaveTypes ({ commit }) {
      ajaxGetDictItems().then(res => {
        if (res['success']) {
          commit('SET_LEAVE_TYPES', res.data)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /* 所有角色 */
    setRoleNames ({ commit }) {
      RoleNames().then(res => {
        if (res.code === 200) {
          commit('SET_ROLE_NAMES', res.result)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /* 所有员工 */
    setEmployees ({ commit }) {
      employeeAll().then(res => {
        if (res['success']) {
          commit('SET_EMPLOYEES', res.data)
        }
      }).catch(error => {
        console.log(error)
      })
    }
  }
}

export default leave
